import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
// --------------------------------------------//
import 'package:pacsun/provider/userProv.dart' show UserProvider;
import 'package:pacsun/provider/putStoreProv.dart' show PutStoreProv;
import 'package:pacsun/provider/sysTagsProvider.dart' show SysTagsProvider;
// --------------------------------------------//
import '../create/createHeader.dart' show ProfileAvatar;
import './userMain.dart' show DividerLine;
import 'package:pacsun/widgets/toastMenu.dart' show ToastMenu;

// --------------------------------------------//
import 'package:pacsun/model/sysUserTagModel.dart' show YouAreTagModel;
import 'package:pacsun/model/userModel.dart' show UserModel;
// --------------------------------------------//
import 'package:pacsun/services/uploadService.dart' show UploadService;

import 'package:pacsun/view/create/mediaPicker/singlePhotoPicker.dart'
    show openImagePicker;
import 'package:pacsun/utils/frontBottomSheet.dart' show showLinkToBottomSheet;
import 'package:pacsun/utils/birthdayPicker.dart' show showBirthdayPicker;
// --------------------------------------------//

class ProfileController {
  final TextEditingController imageUrlController = TextEditingController();
  final TextEditingController nickNameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController dobController = TextEditingController();

  final TextEditingController profileTagsController = TextEditingController();
  final TextEditingController bioController = TextEditingController();
  final TextEditingController tiktokController = TextEditingController();
  final TextEditingController instagramController = TextEditingController();
  final TextEditingController youtubeController = TextEditingController();

  List<String> selectedYouAreList = []; // Changed from String? to List<String>

  void dispose() {
    imageUrlController.dispose();
    nickNameController.dispose();
    emailController.dispose();
    dobController.dispose();
    profileTagsController.dispose();
    bioController.dispose();
    tiktokController.dispose();
    instagramController.dispose();
    youtubeController.dispose();
  }

  Map<String, dynamic> toJson() {
    return {
      'imageUrl': imageUrlController.text,
      'nickname': nickNameController.text,
      'dob': dobController.text.isNotEmpty ? dobController.text : null,
      'youAre': profileTagsController.text, // Now returns a list
      'bio': bioController.text,
      'tiktok': tiktokController.text,
      'instagram': instagramController.text,
      'youtube': youtubeController.text,
    };
  }
}

class UserProfile extends StatefulWidget {
  final int? taskId;
  const UserProfile({super.key, this.taskId});

  @override
  State<UserProfile> createState() => _UserProfileState();
}

class _UserProfileState extends State<UserProfile> {
  final _formKey = GlobalKey<FormState>();
  final _controller = ProfileController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _submitForm() async {
    if (_formKey.currentState?.validate() ?? false) {
      final submittedData = _controller.toJson();

      // Check if any fields were actually changed
      if (submittedData.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('No changes detected')),
        );
        return;
      }

      try {
        await context
            .read<UserProvider>()
            .updateProfile(context, submittedData, widget.taskId);
        // ScaffoldMessenger.of(context).showSnackBar(
        //   const SnackBar(content: Text('Profile updated successfully')),
        // );

        // Navigate based on source
        if (widget.taskId == 2) {
          Navigator.pushNamed(context, '/create');
        } else if (widget.taskId == 3) {
          Navigator.pushNamed(context, '/me');
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error updating profile: ${e.toString()}')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.keyboard_backspace, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Stack(
        children: [
          Form(
            key: _formKey,
            child: CustomScrollView(
              slivers: [
                SliverAppBar(
                  expandedHeight: 192.h,
                  pinned: false,
                  backgroundColor: Colors.transparent,
                  flexibleSpace: FlexibleSpaceBar(
                    background: Container(
                      decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('assets/imgs/img_create_bg.png'),
                            fit: BoxFit.fill),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          SizedBox(height: 136.h),
                          const ProfileAvatar(),
                          SizedBox(height: 12.h),
                          UploadImageButton(controller: _controller),
                        ],
                      ),
                    ),
                  ),
                ),
                SliverPadding(
                  padding:
                      EdgeInsets.only(bottom: 100), // Space for fixed button
                  sliver: SliverToBoxAdapter(
                    child: Material(
                      elevation: 4,
                      borderRadius: BorderRadius.circular(12),
                      color: const Color.fromRGBO(17, 17, 17, 1),
                      child: Column(
                        children: [
                          // const PacsunID(),
                          //const DividerLine(),
                          NickName(controller: _controller),
                          const DividerLine(),
                          const Email(),
                          const DividerLine(),
                          Birthday(controller: _controller),
                          const DividerLine(),
                          Bio(controller: _controller),

                          const DividerLine(),
                          Tags(controller: _controller),
                          const DividerLine(),
                          ProfileTikTok(controller: _controller),
                          const InsLink(),
                          const YoutubeLink(),
                          SizedBox(height: 20), // Extra padding at bottom
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // Fixed positioned submit button
          Positioned(
            bottom: 30,
            left: 20,
            right: 20,
            child: SubmitBtn(onPressed: _submitForm),
          ),
        ],
      ),
    );
  }
}

class SubmitBtn extends StatelessWidget {
  final VoidCallback onPressed;

  const SubmitBtn({super.key, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 300.w,
      height: 55.h,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
            backgroundColor: const Color.fromRGBO(215, 48, 48, 1),
            padding: EdgeInsets.zero,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(27.5.r))),
        onPressed: onPressed,
        child: Text(
          'SUBMIT',
          style: TextStyle(
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w700,
            fontSize: 20.sp,
            height: 1.0,
            letterSpacing: 0,
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

class UploadImageButton extends StatefulWidget {
  final ProfileController controller;

  const UploadImageButton({super.key, required this.controller});

  @override
  State<UploadImageButton> createState() => _UploadImageButtonState();
}

class _UploadImageButtonState extends State<UploadImageButton> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 141,
      height: 31,
      child: OutlinedButton(
        onPressed: () async {
          // Show loading dialog immediately when starting the process
          showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) =>
                const Center(child: CircularProgressIndicator()),
          );

          try {
            // 1. Open image picker
            final selectedImages = await openImagePicker(context);

            if (selectedImages != null && selectedImages.isNotEmpty) {
              // 2. Upload images (keeps loading dialog visible)
              List<String> imgUrlList =
                  await UploadService().uploadImages(selectedImages);

              // 3. Update controller
              widget.controller.imageUrlController.text = imgUrlList[0];

              // 4. Show success message
              if (mounted) {
                Navigator.of(context).pop(); // Close loading dialog
                // ScaffoldMessenger.of(context).showSnackBar(
                //   const SnackBar(content: Text('Image uploaded successfully!')),
                // );
              }
            } else {
              // No images selected - just close loading
              if (mounted) Navigator.of(context).pop();
            }
          } catch (e) {
            // Handle errors
            if (mounted) {
              Navigator.of(context).pop(); // Close loading dialog
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('Upload failed: ${e.toString()}')),
              );
            }
          }
        },
        style: OutlinedButton.styleFrom(
          //  foregroundColor: Colors.white,
          side: BorderSide.none,
          backgroundColor: Color.fromRGBO(217, 217, 217, 0.2),
          padding: const EdgeInsets.only(
            top: 3,
            bottom: 3,
            left: 8,
            right: 8,
          ),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        child: const Text('Update Image',
            style: TextStyle(
                fontFamily: 'Poppins',
                color: Colors.white,
                fontWeight: FontWeight.w500,
                fontSize: 14)),
      ),
    );
  }
}

// class PacsunID extends StatelessWidget {
//   const PacsunID({super.key});

//   @override
//   Widget build(BuildContext context) {
//     return ListTile(
//       horizontalTitleGap: 49.w, // ← Controls spacing between leading and title
//       leading: SizedBox(
//         width: 80.w,
//         child: Text(
//           'Pacsun ID',
//           style: TextStyle(
//             fontSize: 16.sp,
//             letterSpacing: -0.41,
//             fontFamily: 'Poppins',
//             fontWeight: FontWeight.w500,
//             color: Color.fromRGBO(255, 255, 255, 1),
//           ),
//         ),
//       ),
//       title: Selector<UserProvider, int>(
//           selector: (_, provider) => provider.currentUser!.id,
//           builder: (_, id, __) {
//             return Text(
//               '$id',
//               textAlign: TextAlign.left,
//               style: TextStyle(
//                 fontSize: 12.sp,
//                 letterSpacing: -0.41,
//                 fontFamily: 'Poppins',
//                 fontWeight: FontWeight.w400,
//                 color: Color.fromRGBO(255, 255, 255, 1),
//               ),
//             );
//           }),
//     );
//   }
// }

class NickName extends StatefulWidget {
  ProfileController controller;
  NickName({super.key, required this.controller});

  @override
  State<NickName> createState() => _NickNameState();
}

class _NickNameState extends State<NickName> {
  // Add listener variable
  late final TextEditingController _nickNameController;

  @override
  void initState() {
    super.initState();
    _nickNameController = widget.controller.nickNameController;

    // Initialize with provider value
    _nickNameController.text =
        context.read<UserProvider>().currentUser?.nickName ?? '';

    // Add listener to trigger rebuilds when text changes
    _nickNameController.addListener(() {
      if (mounted) setState(() {});
    });
  }

  @override
  void dispose() {
    _nickNameController.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      horizontalTitleGap: 49.w,
      dense: true,
      onTap: () => _showEditNicknameDialog(context, widget.controller),
      leading: SizedBox(
        width: 80.w,
        child: Text(
          'Nickname',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16.sp,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: const Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
      ),
      title: Text(
        // Changed from Selector to simple Text
        _nickNameController.text,
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 12.sp,
          letterSpacing: -0.41,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w400,
          color: const Color.fromRGBO(255, 255, 255, 1),
        ),
      ),
      trailing: GestureDetector(
        onTap: () => _showEditNicknameDialog(context, widget.controller),
        child: Image.asset('assets/icons/icon_pencil.png',
            height: 20, width: 20, color: Colors.white),
      ),
    );
  }

  void _showEditNicknameDialog(
      BuildContext context, ProfileController controller) {
    final textController =
        TextEditingController(text: _nickNameController.text);
    final characterCount = ValueNotifier(textController.text.length);
    final int maxCharacter = 30;
    textController.addListener(() {
      characterCount.value = textController.text.length;
    });

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          backgroundColor: Colors.black,
          appBar: AppBar(
            backgroundColor: Colors.black,
            leading: IconButton(
                icon:
                    const Icon(Icons.arrow_back, size: 24, color: Colors.white),
                onPressed: () => Navigator.pop(context)),
            title: Text(
              'Edit Nickname',
              style: TextStyle(
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w500,
                fontSize: 16,
                height: 22 / 16,
                letterSpacing: 0,
                color: Colors.white,
              ),
            ),
            centerTitle: true,
            actions: [
              Padding(
                padding: const EdgeInsets.only(right: 16),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    minimumSize: const Size(75, 26),
                    backgroundColor: const Color.fromRGBO(215, 48, 48, 1),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25),
                    ),
                    padding: EdgeInsets.zero,
                  ),
                  onPressed: () {
                    final newNickname = textController.text.trim();
                    if (newNickname.isNotEmpty) {
                      _nickNameController.text = newNickname;
                      Navigator.pop(context);
                    }
                  },
                  child: const Text(
                    'SAVE',
                    style: TextStyle(
                      fontFamily: 'Poppins',
                      fontWeight: FontWeight.w600,
                      fontSize: 14,
                      height: 16 / 14,
                      letterSpacing: -0.41,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.only(top: 20, left: 25, right: 25),
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  height: 53,
                  decoration: BoxDecoration(
                    color: const Color.fromRGBO(34, 34, 34, 1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: TextField(
                    controller: textController,
                    cursorColor: Colors.white,
                    style: const TextStyle(color: Colors.white, fontSize: 16),
                    maxLength: maxCharacter,
                    decoration: InputDecoration(
                      contentPadding:
                          const EdgeInsets.symmetric(horizontal: 16),
                      border: InputBorder.none,
                      hintText: 'Enter nickname',
                      hintStyle: const TextStyle(
                        color: Color.fromRGBO(255, 255, 255, 0.3),
                      ),
                      counterText: '',
                      suffix: ValueListenableBuilder<int>(
                        valueListenable: characterCount,
                        builder: (context, count, child) {
                          return Padding(
                            padding: const EdgeInsets.only(right: 8),
                            child: Text(
                              '$count/${maxCharacter}',
                              style: TextStyle(
                                color: count > maxCharacter
                                    ? Colors.red
                                    : const Color.fromRGBO(255, 255, 255, 0.5),
                                fontSize: 12,
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class Email extends StatelessWidget {
  const Email({super.key});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      horizontalTitleGap: 49.w, // Your custom spacing between leading and title

      dense: true,
      leading: SizedBox(
        width: 80.w,
        child: Text(
          'Email',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16.sp,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
      ),
      title: Selector<UserProvider, String?>(
          selector: (_, provider) => provider.currentUser!.email,
          builder: (_, email, __) {
            return Text(
              email ?? '',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 12.sp,
                letterSpacing: -0.41,
                fontFamily: 'Poppins',
                fontWeight: FontWeight.w400,
                color: Color.fromRGBO(255, 255, 255, 1),
              ),
            );
          }),
    );
  }
}

class Birthday extends StatelessWidget {
  final ProfileController controller;

  const Birthday({super.key, required this.controller});

  @override
  Widget build(BuildContext context) {
    //controller.dobController.text = '05/06/2000';
    return Selector<UserProvider, String?>(
        selector: (_, provider) => provider.currentUser?.birthday,
        builder: (_, birthday, __) {
          if (birthday != null && birthday.isNotEmpty) {
            //  controller.selectedDob = DateFormat('MM/dd/yyyy').parse(birthday);
            controller.dobController.text = DateFormat('MM/dd/yyyy')
                .format(DateFormat('MM/dd/yyyy').parse(birthday));
          }

          return ListTile(
            horizontalTitleGap: 49.w,
            dense: true,
            leading: SizedBox(
              width: 80.w,
              child: Text(
                'Birthday',
                style: TextStyle(
                  fontSize: 16.sp,
                  letterSpacing: -0.41,
                  fontFamily: 'Poppins',
                  fontWeight: FontWeight.w500,
                  color: Color.fromRGBO(255, 255, 255, 1),
                ),
              ),
            ),
            title: GestureDetector(
              onTap: () => showBirthdayPicker(
                  context: context,
                  initialDate: controller.dobController.text.isNotEmpty
                      ? DateFormat('MM/dd/yyyy')
                          .parse(controller.dobController.text)
                      : DateTime.now(),
                  onDateSelected: (selectedDate) => controller.dobController
                      .text = DateFormat('MM/dd/yyyy').format(selectedDate)),
              child: AbsorbPointer(
                child: TextFormField(
                  controller: controller.dobController,
                  textAlign: TextAlign.left,
                  cursorColor: Colors.white,
                  style: TextStyle(
                    fontSize: 12.sp,
                    letterSpacing: -0.41,
                    fontFamily: 'Poppins',
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 1),
                  ),
                  decoration: InputDecoration(
                    hintText: 'Please select',
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.3),
                    ),
                    border: InputBorder.none,
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please select your date of birth';
                    }
                    return null;
                  },
                ),
              ),
            ),
            trailing: GestureDetector(
              onTap: () => showBirthdayPicker(
                context: context,
                initialDate: controller.dobController.text.isNotEmpty
                    ? DateFormat('MM/dd/yyyy')
                        .parse(controller.dobController.text)
                    : DateTime.now(),
                onDateSelected: (selectedDate) => controller.dobController
                    .text = DateFormat('MM/dd/yyyy').format(selectedDate),
              ),
              child: Image.asset('assets/icons/icon_pencil.png',
                  height: 20, width: 20, color: Colors.white),
            ),
          );
        });
  }
}

class Tags extends StatelessWidget {
  final ProfileController controller;

  const Tags({super.key, required this.controller});

  // 将 ID 字符串转换为 name 列表用于显示
  List<String> _convertIdsToNames(String? ids, List<YouAreTagModel> sysTags) {
    if (ids == null || ids.isEmpty) return [];

    List<String> idList =
        ids.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
    List<String> names = [];

    for (String idStr in idList) {
      try {
        int id = int.parse(idStr);
        YouAreTagModel? tag = sysTags.firstWhere((tag) => tag.id == id,
            orElse: () => YouAreTagModel(id: -1, name: ''));
        if (tag.id != -1) {
          names.add(tag.name);
        }
      } catch (e) {
        // 忽略无效的 ID
      }
    }

    return names;
  }

  // 将 ID 字符串转换为 ID 列表
  List<int> _convertIdsToList(String? ids) {
    if (ids == null || ids.isEmpty) return [];

    return ids
        .split(',')
        .map((e) => e.trim())
        .where((e) => e.isNotEmpty)
        .map((e) {
          try {
            return int.parse(e);
          } catch (e) {
            return -1;
          }
        })
        .where((id) => id != -1)
        .toList();
  }

  // 将 ID 列表转换为 ID 字符串
  String _convertListToIds(List<int> ids) => ids.join(',');

  Future<void> _showProfileSelectionModal(BuildContext context) async {
    await showModalBottomSheet(
      context: context,
      backgroundColor: const Color.fromRGBO(34, 34, 34, 1),
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(12))),
      isScrollControlled: true,
      builder: (BuildContext context) {
        // 将 selectedIds 移到 StatefulBuilder 外部，避免重复初始化
        List<int> selectedIds =
            _convertIdsToList(context.read<UserProvider>().currentUser?.youAre);

        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            return Selector<SysTagsProvider, List<YouAreTagModel>>(
              selector: (_, provider) => provider.sysTags,
              builder: (_, sysTags, __) {
                return Padding(
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: Container(
                    padding:
                        const EdgeInsets.only(left: 16, right: 16, bottom: 38),
                    decoration: const BoxDecoration(
                      color: Color.fromRGBO(34, 34, 34, 1),
                      borderRadius:
                          BorderRadius.vertical(top: Radius.circular(12)),
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // Header row
                        SizedBox(
                          height: 44,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              IconButton(
                                icon: const Icon(Icons.close,
                                    color: Colors.white, size: 24),
                                onPressed: () => Navigator.pop(context),
                              ),
                              const Text(
                                'Style Profile',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                  fontFamily: 'Poppins',
                                ),
                              ),
                              Opacity(
                                opacity: selectedIds.isEmpty ? 0.2 : 1.0,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                    minimumSize: const Size(75, 26),
                                    backgroundColor:
                                        const Color.fromRGBO(215, 48, 48, 1),
                                    shape: RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(25)),
                                    elevation: 0,
                                    padding: EdgeInsets.zero,
                                  ),
                                  onPressed: selectedIds.isEmpty
                                      ? null
                                      : () {
                                          String idsString =
                                              _convertListToIds(selectedIds);
                                          controller.profileTagsController
                                              .text = idsString;
//comment
                                          context
                                              .read<UserProvider>()
                                              .updateUserInfo(
                                                  UserModel(youAre: idsString));

                                          Navigator.pop(context);
                                        },
                                  child: Container(
                                    width: 35,
                                    height: 16,
                                    alignment: Alignment.center,
                                    child: const Text(
                                      'SAVE',
                                      style: TextStyle(
                                        fontFamily: 'Poppins',
                                        fontWeight: FontWeight.w600,
                                        fontSize: 14,
                                        height: 16 / 14,
                                        letterSpacing: -0.41,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),

                        // Divider
                        Container(
                          height: 1,
                          color: const Color.fromRGBO(60, 60, 67, 0.36),
                          margin: const EdgeInsets.only(bottom: 16),
                        ),

                        // Tag selection area
                        Flexible(
                          child: SingleChildScrollView(
                            child: Wrap(
                              spacing: 12,
                              runSpacing: 12,
                              children: sysTags.map((tag) {
                                final isSelected = selectedIds.contains(tag.id);
                                return GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      if (isSelected) {
                                        selectedIds.remove(tag.id);
                                      } else {
                                        selectedIds.add(tag.id);
                                      }
                                    });
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 20, vertical: 10),
                                    // constraints:
                                    //     const BoxConstraints(minWidth: 130),
                                    decoration: BoxDecoration(
                                      color: isSelected
                                          ? Colors.white
                                          : const Color.fromRGBO(
                                              99, 99, 99, 0.5),
                                      borderRadius: BorderRadius.circular(30),
                                      border: Border.all(
                                        color: isSelected
                                            ? Colors.transparent
                                            : const Color.fromRGBO(
                                                255, 255, 255, 0.2),
                                        width: 1,
                                      ),
                                    ),
                                    child: Text(
                                      tag.name,
                                      style: TextStyle(
                                          fontFamily: 'Poppins',
                                          fontWeight: FontWeight.w500,
                                          fontSize: 14,
                                          height: 16 / 14,
                                          letterSpacing: -0.41,
                                          color: isSelected
                                              ? Colors.black
                                              : Colors.white),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      dense: true,
      leading: const Text(
        "Tags",
        style: TextStyle(
            fontSize: 16,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(255, 255, 255, 1)),
      ),
      title: Selector2<UserProvider, SysTagsProvider, String>(
        selector: (_, userProvider, sysTagsProvider) {
          String? userYouAre = userProvider.currentUser?.youAre;
          List<YouAreTagModel> sysTags = sysTagsProvider.sysTags;

          if (userYouAre != null && userYouAre.isNotEmpty) {
            // 将 ID 字符串转换为 name 列表，然后连接成显示字符串
            List<String> names = _convertIdsToNames(userYouAre, sysTags);
            return names.join(', ');
          }
          return '';
        },
        builder: (context, displayText, child) {
          // 初始化 controller 的值为用户的 youAre ID 字符串
          String? userYouAre = context.read<UserProvider>().currentUser?.youAre;
          if (userYouAre != null &&
              controller.profileTagsController.text.isEmpty) {
            controller.profileTagsController.text = userYouAre;
          }

          return GestureDetector(
            onTap: () => _showProfileSelectionModal(context),
            child: AbsorbPointer(
              child: Container(
                alignment: Alignment.topCenter,
                child: Text(
                  displayText.isEmpty ? 'Please select' : displayText,
                  style: TextStyle(
                    fontSize: 12,
                    letterSpacing: -0.41,
                    fontFamily: 'Poppins',
                    fontWeight: FontWeight.w400,
                    color: displayText.isEmpty
                        ? const Color.fromRGBO(255, 255, 255, 0.3)
                        : const Color.fromRGBO(255, 255, 255, 1),
                  ),
                  textAlign: TextAlign.left,
                ),
              ),
            ),
          );
        },
      ),
      // trailing: Image.asset('assets/icons/icon_forwardArrow.png',
      //     height: 13, width: 7, color: Colors.white),

      trailing: GestureDetector(
        onTap: () => _showProfileSelectionModal(context),
        child: Image.asset(
          'assets/icons/icon_pencil.png',
          height: 20,
          width: 20,
          color: Colors.white,
        ),
      ),
    );
  }
}

class Bio extends StatefulWidget {
  final ProfileController controller;
  const Bio({super.key, required this.controller});

  @override
  State<Bio> createState() => _BioState();
}

class _BioState extends State<Bio> {
  late final TextEditingController _bioController;

  @override
  void initState() {
    super.initState();
    _bioController = widget.controller.bioController;
    _bioController.text = context.read<UserProvider>().currentUser?.bio ?? '';
    _bioController.addListener(() {
      if (mounted) setState(() {});
    });
  }

  @override
  void dispose() {
    _bioController.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      horizontalTitleGap: 49.w,
      dense: true,
      onTap: () => _showEditBioDialog(context, widget.controller),
      leading: SizedBox(
        width: 80.w,
        child: Text(
          'Bio',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16.sp,
            letterSpacing: -0.41,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w500,
            color: const Color.fromRGBO(255, 255, 255, 1),
          ),
        ),
      ),
      title: Text(
        _bioController.text,
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 12.sp,
          letterSpacing: -0.41,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w400,
          color: const Color.fromRGBO(255, 255, 255, 1),
        ),
      ),
      trailing: GestureDetector(
        onTap: () => _showEditBioDialog(context, widget.controller),
        child: Image.asset(
          'assets/icons/icon_pencil.png',
          height: 20,
          width: 20,
          color: Colors.white,
        ),
      ),
    );
  }

  void _showEditBioDialog(BuildContext context, ProfileController controller) {
    final textController = TextEditingController(text: _bioController.text);
    final characterCount = ValueNotifier(textController.text.length);

    textController.addListener(() {
      characterCount.value = textController.text.length;
    });

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          backgroundColor: Colors.black,
          appBar: AppBar(
            backgroundColor: Colors.black,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back, size: 24, color: Colors.white),
              onPressed: () => Navigator.pop(context),
            ),
            title: Text(
              'Edit Bio',
              style: TextStyle(
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w500,
                fontSize: 16,
                height: 22 / 16,
                letterSpacing: 0,
                color: Colors.white,
              ),
            ),
            centerTitle: true,
            actions: [
              Padding(
                padding: const EdgeInsets.only(right: 16),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    minimumSize: const Size(75, 26),
                    backgroundColor: const Color.fromRGBO(215, 48, 48, 1),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25),
                    ),
                    padding: EdgeInsets.zero,
                  ),
                  onPressed: () {
                    final newBio = textController.text.trim();
                    _bioController.text = newBio;
                    Navigator.pop(context);
                  },
                  child: const Text(
                    'SAVE',
                    style: TextStyle(
                      fontFamily: 'Poppins',
                      fontWeight: FontWeight.w600,
                      fontSize: 14,
                      height: 16 / 14,
                      letterSpacing: -0.41,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.only(top: 20, left: 25, right: 25),
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  height: 150, // Larger box for bio input
                  decoration: BoxDecoration(
                    color: const Color.fromRGBO(34, 34, 34, 1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: TextField(
                    controller: textController,
                    cursorColor: Colors.white,
                    maxLines: 5, // Allow multiple lines
                    maxLength: 500, // 100 character limit
                    style: const TextStyle(color: Colors.white, fontSize: 16),
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.all(16),
                      border: InputBorder.none,
                      hintText: 'Tell us about yourself...',
                      hintStyle: const TextStyle(
                          color: Color.fromRGBO(255, 255, 255, 0.3)),
                      counterText: '',
                      suffix: ValueListenableBuilder<int>(
                        valueListenable: characterCount,
                        builder: (context, count, child) {
                          return Padding(
                            padding: const EdgeInsets.only(bottom: 8, right: 8),
                            child: Text(
                              '$count/500',
                              style: TextStyle(
                                color: count > 500
                                    ? Colors.red
                                    : const Color.fromRGBO(255, 255, 255, 0.5),
                                fontSize: 12,
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class ProfileTikTok extends StatelessWidget {
  final ProfileController controller;
  const ProfileTikTok({super.key, required this.controller});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      horizontalTitleGap: 13,
      dense: true,
      leading: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Image.asset('assets/imgs/img_tiktok.png', width: 20, height: 20),
      ),
      title: Text(
        'TikTok',
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 16,
          letterSpacing: -0.41,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w500,
          color: Color.fromRGBO(255, 255, 255, 1),
        ),
      ),
      trailing: SizedBox(
        height: 25,
        child: Selector<UserProvider, bool>(
            selector: (_, provider) =>
                provider.currentUser?.connected?['tiktok'] != null,
            builder: (context, isLinkTiktok, child) {
              print(
                  "provider.currentUser?.connected?['tiktok']:  ${context.read<UserProvider>().currentUser?.connected?['tiktok']}");
              return isLinkTiktok
                  ? Image.asset('assets/icons/icon_green_complete.png',
                      height: 20, width: 20)
                  : OutlinedButton(
                      onPressed: () => showLinkToBottomSheet(context, 'tt'),
                      style: OutlinedButton.styleFrom(
                        side: BorderSide.none,
                        backgroundColor: Color.fromRGBO(215, 48, 48, 1),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.5)),
                      ),
                      child: const Text(
                        'Connect',
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                          letterSpacing: -0.41,
                          fontSize: 14,
                        ),
                      ),
                    );
            }),
      ),
    );
  }
}

class TTUploadScreen extends StatefulWidget {
  const TTUploadScreen({super.key});

  @override
  State<TTUploadScreen> createState() => _TTUploadScreenState();
}

class _TTUploadScreenState extends State<TTUploadScreen> {
  bool _isUploading = false;

  Future<void> _handleImageUpload() async {
    if (_isUploading) return;

    setState(() => _isUploading = true);

    try {
      // 1. Open image picker
      final selectedImages = await openImagePicker(context);
      if (selectedImages == null || selectedImages.isEmpty) {
        setState(() => _isUploading = false);
        return;
      }

      // 2. Upload images
      final imageUrls = await UploadService().uploadImages(selectedImages);
      if (imageUrls.isNotEmpty) {
        context.read<PutStoreProv>().updateStoreFrontImage(imageUrls.first);

        // 3. You can add your updating logic here
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Upload failed: ${e.toString()}')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isUploading = false);
      }
    }
  }

  Widget _buildUploadButton() {
    return InkWell(
      onTap: _isUploading ? null : _handleImageUpload,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        width: 112.w,
        height: 112.h,
        decoration: BoxDecoration(
          color: const Color.fromRGBO(17, 17, 17, 1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: _isUploading
            ? const Center(
                child: CircularProgressIndicator(color: Colors.white))
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.add, size: 24, color: Colors.white),
                  Padding(
                    padding: EdgeInsets.only(top: 8.h),
                    child: Text(
                      'UPLOAD\nSCREENSHOT',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.w400,
                        fontSize: 14.sp,
                        height: 16 / 14,
                        letterSpacing: -0.41,
                        color: Colors.white.withAlpha(128),
                      ),
                    ),
                  ),
                ],
              ),
      ),
    );
  }

  Widget _buildImagePreview(String _imageUrl) {
    return Container(
      width: 112.w,
      height: 112.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(17, 17, 17, 1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Builder(builder: (context) {
          return CachedNetworkImage(
            imageUrl: _imageUrl,
            fit: BoxFit.cover,
            placeholder: (context, url) => const Center(
                child: CircularProgressIndicator(color: Colors.white)),
            errorWidget: (context, url, error) => const Icon(Icons.error),
          );
        }),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final imageUrl = context.select<PutStoreProv, String?>(
        (provider) => provider.uploadStoreFrontUrl);

    return imageUrl != null
        ? _buildImagePreview(imageUrl)
        : _buildUploadButton();
  }
}

class TTIdInput extends StatelessWidget {
  const TTIdInput({super.key});

  @override
  Widget build(BuildContext context) {
    return Selector<UserProvider, String?>(
      selector: (_, provider) => provider.currentUser?.connected?['tiktok'],
      builder: (context, ttOpenid, child) {
        final controller = TextEditingController(text: ttOpenid);
        final focusNode = FocusNode();

        // Update controller when unionId changes externally
        if (ttOpenid != controller.text) {
          controller.text = ttOpenid ?? '';
        }

        return Center(
          child: TextField(
            controller: controller,
            focusNode: focusNode,
            style: TextStyle(
              color: Colors.white,
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w400,
              fontSize: 14,
              height: 16 / 14,
              letterSpacing: -0.41,
            ),
            cursorColor: Colors.white,
            decoration: InputDecoration(
              filled: true,
              hintText: 'Please input TikTok ID',
              hintStyle: TextStyle(
                color: Colors.white.withAlpha(77),
                fontFamily: 'Poppins',
                fontWeight: FontWeight.w400,
                fontSize: 14,
                height: 16 / 14,
                letterSpacing: -0.41,
              ),
              contentPadding: EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 18,
              ),
              fillColor: Color.fromRGBO(17, 17, 17, 1),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide.none,
              ),
              isDense: true,
            ),
            // onChanged: (value) {
            //   // Update the provider when text changes
            //   final provider = context.read<SocialMediaProvider>();
            //   if (provider.tikTokAccount != null) {
            //     provider.TTSetValue(
            //         provider.tikTokAccount!.copyWith(unionId: value));
            //   }
            // },
            onSubmitted: (value) {
              focusNode.unfocus(); // Hide keyboard on submit
            },
          ),
        );
      },
    );
  }
}

class TTProfileLink extends StatelessWidget {
  const TTProfileLink({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextField(
        style: TextStyle(
          color: Colors.white,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w400,
          fontSize: 14,
          height: 16 / 14, // line-height: 16px (16/14 font-size)
          letterSpacing: -0.41,
        ),
        cursorColor: Colors.white,
        decoration: InputDecoration(
          filled: true,
          hintText: 'Please input TikTok Profile link',
          hintStyle: TextStyle(
            color: Colors.white.withAlpha(77), // 30% opacity
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w400,
            fontSize: 14,
            height: 16 / 14,
            letterSpacing: -0.41,
          ),
          // Control hint text padding
          contentPadding: EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 18, // Adjust vertical padding as needed
          ),
          fillColor: Color.fromRGBO(17, 17, 17, 1),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: BorderSide.none,
          ),
          // Ensures vertical alignment matches your requirements
          isDense: true,
        ),
      ),
    );
  }
}

class YoutubeLink extends StatelessWidget {
  const YoutubeLink({super.key});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      horizontalTitleGap: 13, // ← Controls spacing between leading and title
      dense: true,
      leading: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Image.asset('assets/imgs/img_youtube.png',
              width: 20, height: 20)),
      title: Text(
        'YouTube',
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 16,
          letterSpacing: -0.41,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w500,
          color: Color.fromRGBO(255, 255, 255, 1),
        ),
      ),
      trailing: SizedBox(
        height: 25,
        child: OutlinedButton(
          // onPressed: () => showLinkToBottomSheet(context, ''),
          onPressed: () {
            ToastMenu.showToast(context, 'Function under development');
          },
          style: OutlinedButton.styleFrom(
            side: BorderSide.none,
            backgroundColor: Color.fromRGBO(215, 48, 48, 1),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.5),
            ),
          ),
          child: const Text('Connect',
              style: TextStyle(
                  fontFamily: 'Poppins',
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  letterSpacing: -0.41,
                  fontSize: 14)),
        ),
      ),
    );
  }
}

class InsLink extends StatelessWidget {
  const InsLink({super.key});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      horizontalTitleGap: 13, // ← Controls spacing between leading and title
      dense: true,
      leading: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Image.asset('assets/imgs/img_ins.png', width: 20, height: 20)),
      title: Text(
        'Instagram',
        textAlign: TextAlign.left,
        style: TextStyle(
          fontSize: 16,
          letterSpacing: -0.41,
          fontFamily: 'Poppins',
          fontWeight: FontWeight.w500,
          color: Color.fromRGBO(255, 255, 255, 1),
        ),
      ),
      trailing: SizedBox(
        height: 25,
        child: OutlinedButton(
          //   onPressed: () => showLinkToBottomSheet(context, 'ins'),
          onPressed: () {
            ToastMenu.showToast(context, 'Function under development');
          },
          style: OutlinedButton.styleFrom(
            side: BorderSide.none,
            backgroundColor: Color.fromRGBO(215, 48, 48, 1),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.5),
            ),
          ),
          child: const Text('Connect',
              style: TextStyle(
                  fontFamily: 'Poppins',
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  letterSpacing: -0.41,
                  fontSize: 14)),
        ),
      ),
    );
  }
}
